<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="`${drawerProps.title}车间`">
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="车间编码" prop="workshopCode">
        <el-input v-model="drawerProps.row!.workshopCode" placeholder="请输入车间编码" clearable :disabled="drawerProps.isView || !!drawerProps.row!.id"></el-input>
      </el-form-item>
      <el-form-item label="车间名称" prop="workshopName">
        <el-input v-model="drawerProps.row!.workshopName" placeholder="请输入车间名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="所属工厂" prop="factoryId">
        <el-select v-model="drawerProps.row!.factoryId" placeholder="请选择工厂" style="width: 100%">
          <el-option
            v-for="factory in factoryOptions"
            :key="factory.id"
            :label="factory.factoryName"
            :value="factory.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="车间类型" prop="workshopType">
        <el-select v-model="drawerProps.row!.workshopType" placeholder="请选择车间类型" style="width: 100%">
          <el-option label="生产车间" value="PRODUCTION" />
          <el-option label="装配车间" value="ASSEMBLY" />
          <el-option label="质检车间" value="QUALITY" />
          <el-option label="仓储车间" value="WAREHOUSE" />
        </el-select>
      </el-form-item>
      <el-form-item label="车间面积" prop="area">
        <el-input-number v-model="drawerProps.row!.area" :min="0" :precision="2" placeholder="请输入车间面积" style="width: 100%">
          <template #append>㎡</template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="负责人" prop="manager">
        <el-input v-model="drawerProps.row!.manager" placeholder="请输入负责人" clearable></el-input>
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="drawerProps.row!.phone" placeholder="请输入联系电话" clearable></el-input>
      </el-form-item>
      <el-form-item label="车间状态" prop="status" v-if="drawerProps.isView">
        <el-tag :type="getStatusType(drawerProps.row!.status)">{{ getStatusText(drawerProps.row!.status) }}</el-tag>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="drawerProps.row!.description" :rows="4" type="textarea" placeholder="请输入车间描述"></el-input>
      </el-form-item>
      <el-form-item label="创建人" prop="createdBy" v-if="drawerProps.isView && drawerProps.row!.createdBy">
        <el-input v-model="drawerProps.row!.createdBy" disabled></el-input>
      </el-form-item>
      <el-form-item label="创建时间" prop="createdTime" v-if="drawerProps.isView && drawerProps.row!.createdTime">
        <el-input v-model="drawerProps.row!.createdTime" disabled></el-input>
      </el-form-item>
      <el-form-item label="更新人" prop="updatedBy" v-if="drawerProps.isView && drawerProps.row!.updatedBy">
        <el-input v-model="drawerProps.row!.updatedBy" disabled></el-input>
      </el-form-item>
      <el-form-item label="更新时间" prop="updatedTime" v-if="drawerProps.isView && drawerProps.row!.updatedTime">
        <el-input v-model="drawerProps.row!.updatedTime" disabled></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="drawer-button-box">
        <el-button @click="drawerVisible = false">取消</el-button>
        <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="WorkshopForm">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Workshop, createWorkshop, updateWorkshop } from "@/api/modules/workshop";
import { getFactoryList, type Factory } from "@/api/modules/factory";
import { PageHelper } from "@/utils/pageHelper";

const rules = reactive({
  workshopCode: [{ required: true, message: "请输入车间编码", trigger: "blur" }],
  workshopName: [{ required: true, message: "请输入车间名称", trigger: "blur" }],
  factoryId: [{ required: true, message: "请选择所属工厂", trigger: "change" }],
  workshopType: [{ required: true, message: "请选择车间类型", trigger: "change" }]
});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<Workshop.WorkshopListItem>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});

const factoryOptions = ref<Factory.FactoryListItem[]>([]);

// 获取工厂选项
const getFactoryOptions = async () => {
  try {
    const res = await getFactoryList({ current: 1, size: 1000 });
    const pageData = PageHelper.parsePage<Factory.FactoryListItem>(res.data);
    factoryOptions.value = pageData.records;
  } catch (error) {
    console.error("获取工厂列表失败:", error);
  }
};

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    ACTIVE: "success",
    INACTIVE: "warning",
    MAINTENANCE: "info"
  };
  return statusMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    ACTIVE: "启用",
    INACTIVE: "禁用",
    MAINTENANCE: "维护中"
  };
  return statusMap[status] || status;
};

// 接收父组件传过来的参数
const open = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
  getFactoryOptions();
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      const isEdit = !!drawerProps.value.row.id;
      
      if (isEdit) {
        // 编辑车间
        const params = {
          workshopName: drawerProps.value.row.workshopName!,
          factoryId: drawerProps.value.row.factoryId!,
          workshopType: drawerProps.value.row.workshopType!,
          area: drawerProps.value.row.area,
          manager: drawerProps.value.row.manager,
          phone: drawerProps.value.row.phone,
          description: drawerProps.value.row.description
        };
        await updateWorkshop(drawerProps.value.row.id!, params);
        ElMessage.success("车间更新成功！");
      } else {
        // 新增车间
        const params = {
          workshopCode: drawerProps.value.row.workshopCode!,
          workshopName: drawerProps.value.row.workshopName!,
          factoryId: drawerProps.value.row.factoryId!,
          workshopType: drawerProps.value.row.workshopType!,
          area: drawerProps.value.row.area,
          manager: drawerProps.value.row.manager,
          phone: drawerProps.value.row.phone,
          description: drawerProps.value.row.description
        };
        await createWorkshop(params);
        ElMessage.success("车间创建成功！");
      }

      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.error("提交失败:", error);
      ElMessage.error("操作失败！");
    }
  });
};

onMounted(() => {
  getFactoryOptions();
});

defineExpose({
  open
});
</script>

<style scoped>
.drawer-button-box {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>